#!/usr/bin/env bash
set -euo pipefail
# Usage: coreos-assembler <cmd> ...
# Currently this just wraps the two binaries we have today
# under a global entrypoint with subcommands.

# Set PYTHONUNBUFFERED=1 so that we get unbuffered output. We should
# be able to do this on the shebang lines but env doesn't support args
# right now. In Fedora we should be able to use the `env -S` option.
export PYTHONUNBUFFERED=1

# docker/podman don't run through PAM, but we want this set for the privileged
# (non-virtualized) path
export USER="${USER:-$(id -nu)}"

# When trying to connect to libvirt we get "Failed to find user record
# for uid" errors if there is no entry for our UID in /etc/passwd.
# This was taken from 'Support Arbitrary User IDs' section of:
#   https://docs.openshift.com/container-platform/3.10/creating_images/guidelines.html
if ! whoami &> /dev/null; then
  # We need to make sure we set $HOME in the /etc/passwd file because
  # if we don't libvirt will try to use `/` and we will get permission
  # issues
  export HOME="/var/tmp/${USER_NAME:-default}" && mkdir -p "$HOME"
  if [ -w /etc/passwd ]; then
      echo "${USER_NAME:-default}:x:$(id -u):0:${USER_NAME:-default} user:${HOME}:/sbin/nologin" >> /etc/passwd
  fi
fi

# Ensure we've unshared our mount namespace so
# the later umount doesn't affect the host potentially
if [ -e /sys/fs/selinux/status ]; then
    if [ -z "${coreos_assembler_unshared:-}" ]; then
        exec sudo -E -- env coreos_assembler_unshared=1 unshare -m -- runuser -u "${USER}" -- "$0" "$@"
    else
        # Work around https://github.com/containers/libpod/issues/1448
        # https://github.com/cgwalters/coretoolbox/blob/04e36894cdb912cd4d4c91b26436c57a2d96707d/src/coretoolbox.rs#L616
        sudo mount --bind /usr/share/empty /sys/fs/selinux
    fi
fi

cmd=${1:-}
# commands we'd expect to use in the local dev path
build_commands="init fetch build run prune clean list"
# commands more likely to be used in a prod pipeline only
advanced_build_commands="buildprep buildupload oc-adm-release upload-oscontainer"
buildextend_commands="aliyun aws azure digitalocean exoscale gcp ibmcloud live metal metal4k openstack qemu vmware vultr"
utility_commands="aws-replicate compress generate-hashlist koji-upload kola remote-prune sign tag"
other_commands="shell meta"
if [ -z "${cmd}" ]; then
    echo Usage: "coreos-assembler CMD ..."
    echo "Build commands:"
    for bin in ${build_commands}; do
        echo "  ${bin}"
    done # don't sort these ones, they're roughly in the order they're used

    echo "Advanced build commands:"
    for bin in ${advanced_build_commands}; do
        echo "  ${bin}"
    done && for bin in ${buildextend_commands}; do
        echo "  buildextend-${bin}"
    done | sort

    echo "Utility commands:"
    for bin in ${utility_commands}; do
        echo "  ${bin}"
    done | sort

    echo "Other commands:"
    for bin in ${other_commands}; do
        echo "  ${bin}"
    done | sort
    exit 1
fi
shift

COSA_META_SCHEMA="${COSA_META_SCHEMA:-/usr/lib/coreos-assembler/schema/v1.json}"
schema_override="${PWD}/src/config/schema.json"
if [ -e "${schema_override}" ]; then
    COSA_META_SCHEMA=$(realpath "${schema_override}")
fi
export COSA_META_SCHEMA


target=/usr/lib/coreos-assembler/cmd-${cmd}
if test -x "${target}"; then
    exec "${target}" "$@"
fi

echo "Unknown command: ${cmd}" 1>&2
exit 1
